<?php
// 应用公共文件
use think\facade\Db;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use create_order_number\SnowFlake;

    /**
     * 截取url可删除
     * $url url地址
     **/
	function cutOutUrl($url){
		$del_url = public_path().substr($url,strpos($url,'/',8));
		$url = substr($url,strpos($url,'/',8));
		return array('del_url'=>$del_url,'url'=>$url);
	}
    /**
     * 私密 隐藏 隐私 姓名
     * 姓名隐藏后面
     * 卜**
     * $userName 用户姓名
     **/
    function substrCut($userName)
    {
        $strlen = mb_strlen($userName, 'utf-8');
        $firstStr = mb_substr($userName, 0, 1, 'utf-8');
        $lastStr = mb_substr($userName, -1, 1, 'utf-8');
        //若名字长度==2，则 姓** 否则姓*名
        //$resultName = ($strlen == 2) ? $firstStr . str_repeat('**', mb_strlen($userName, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2). $lastStr ;
        //全设为姓**
        $resultName = ($strlen == 2) ? $firstStr . str_repeat('**', mb_strlen($userName, 'utf-8') - 1) : $firstStr . str_repeat("*",  2) ;
        return $resultName;
    }
    /**
     * 私密 隐藏 隐私 手机号码
     * 手机号码隐藏4位中间
     * 176****3972
     * $userPhone 电话号码
    **/
    function substrPhone($userPhone)
    {
        $strlen = mb_strlen($userPhone, 'utf-8');
        $firstStr = mb_substr($userPhone, 0, 3, 'utf-8');
        $lastStr = mb_substr($userPhone, 7, 4, 'utf-8');

        $resultPhone =  $firstStr . str_repeat("*", $strlen - 7).$lastStr;
        return $resultPhone;
    }

    /**
     *将时间转为几秒钟，几分钟
     *
     */
    function time_ago($posttime){
        //当前时间的时间戳
        $nowtimes = strtotime(date('Y-m-d H:i:s'),time());
        //之前时间参数的时间戳
        $posttimes = strtotime($posttime);
        //相差时间戳
        $counttime = $nowtimes - $posttimes;
        //进行时间转换
        if($counttime<=10){
            return '刚刚';
        }else if($counttime>10 && $counttime<=30){
            return '刚才';
        }else if($counttime>30 && $counttime<=60){
            return '刚一会';
        }else if($counttime>60 && $counttime<=120){
            return '1分钟前';
        }else if($counttime>120 && $counttime<=180){
            return '2分钟前';
        }else if($counttime>180 && $counttime<3600){
            return intval(($counttime/60)).'分钟前';
        }else if($counttime>=3600 && $counttime<3600*24){
            return intval(($counttime/3600)).'小时前';
        }else if($counttime>=3600*24 && $counttime<3600*24*2){
            return '昨天';
        }else if($counttime>=3600*24*2 && $counttime<3600*24*3){
            return '前天';
        }else if($counttime>=3600*24*3 && $counttime<=3600*24*20){
            return intval(($counttime/(3600*24))).'天前';
        }else{
            return $posttime;
        }
    }

    /**
     * 获取富文本编译器中的所有图片
     * @param string $contentStr
     * @return array
     */
    function getPatternMatchImages($contentStr = "")
    {
        $img_src_arr = [];
        $pattern_imgTag = '/<img\b.*?(?:\>|\/>)/i';
        preg_match_all($pattern_imgTag,$contentStr,$match_img);
        if (isset($match_img[0]))
        {
            foreach ($match_img[0] as $key => $img_tag)
            {
                $pattern_src = '/\bsrc\b\s*=\s*[\'\"]?([^\'\"]*)[\'\"]?/i';
                preg_match_all($pattern_src,$img_tag,$matchSrc);
                if (isset($matchSrc[1]))
                {
                    foreach ($matchSrc[1] as $src)
                    {
                        $img_src_arr[] = $src;
                    }
                }
            }
        }
        return $img_src_arr;
    }
/**
 * 云信通短信平台api
 *查询短信剩余量
 *  $userName 账户名
 *  $pssword 密码
 */
function getMessageSum($userName,$password){
    /**{"code":0,"message":"处理成功","balance":1}**/
    $url = "http://119.23.144.191:8001/sms/api/getBalance";
    $udata = [];
    $udata['userName'] = $userName;
    $udata['timestamp'] =msectimes();//ms //strtotime(date("Y-m-d H:i:s"))*100
    $udata['sign'] = md5($udata['userName'].$udata['timestamp'].md5($password));
    $header = [
        'Accept:application/json',
        'Content-Type:application/json;charset=utf-8'
    ];
    $res = req_Posts($url,$header,json_encode($udata));
    return $res;
}
/**
 * 云信通短信平台api
 *  $userName 账户名
 *  $pssword 密码
 *  $phone 发送的手机号码
 *  $content 发送的内容 【必须给短信平台备案才可以发送】
*/

function shortMessage($userName,$pssword,$phone,$content){
    $url = "http://119.23.144.191:8001/sms/api/sendMessageOne";
    $udata = [];
    $udata['userName'] = $userName;
    $udata['pssword'] = $pssword;
    $udata['messageList'] =array(['phone'=>(string)$phone,'content'=>$content]);
    $udata['timestamp'] =msectimes();//ms //strtotime(date("Y-m-d H:i:s"))*100
    $udata['sign'] = md5($udata['userName'].$udata['timestamp'].md5($udata['pssword']));
    $header = [
        'Accept:application/json',
        'Content-Type:application/json;charset=utf-8'
    ];
    $res = req_Posts($url,$header,json_encode($udata));
    return $res;
}
//返回当前的毫秒时间戳
function msectimes(){
    list($msec, $sec) = explode(' ', microtime());
    $msectime = (int)sprintf('%.0f',(floatval($msec) + floatval($sec)) * 1000);
    return $msectime;
}
//php发送Post带header头部请求
function req_Posts($url,$header,$udata)
{
    $timeout = 5;
    $con = curl_init();
    curl_setopt($con, CURLOPT_URL, $url);
    curl_setopt($con, CURLOPT_FORBID_REUSE, 1);
    curl_setopt($con, CURLOPT_FRESH_CONNECT, 1);
    curl_setopt($con, CURLINFO_HEADER_OUT, true);
    curl_setopt($con, CURLOPT_HTTPHEADER, $header);
    curl_setopt($con, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($con, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($con, CURLOPT_POST,true);
    curl_setopt($con, CURLOPT_POSTFIELDS,$udata);//http_build_query($udata)
    curl_setopt($con, CURLOPT_HEADER, false);
    curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($con, CURLOPT_TIMEOUT, (int)$timeout);
    $p_res = curl_exec($con);
    // $a = curl_getinfo($con, CURLINFO_HEADER_OUT);
    // var_dump($a);
    curl_close($con);
    if ($p_res) {
        return $p_res;
    } else {
        return false;
    }
}
/**
 * 创建qc二维码
*/
function create_qrcode($value){

    include_once '../extend/qrcode/phpqrcode.php';
    $value = $value;
    $str = '';
    $errorCorrectionLevel='L';//容错级别
    $matrixPointSize = 5;//生成图片大小
    $filename='';
    if(empty($str)){
        $filename='qrcode/'.time().'.png';
    }else{
        $filename='qrcode/'.$str.'.png';
    }
    \QRcode::png($value,$filename,$errorCorrectionLevel,$matrixPointSize,2);
    $path=$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.$filename;
    //echo '<img src='.$path.'>';
	return $path;
}

/**
 * 生成随机字符串
*/
function rand_code()
{
    $str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $str = str_shuffle($str);
    $str = substr($str, 0, 32);
    return $str;
}

/**
 * php发送curl的get请求
 * $curl：url地址
 */
function req_Get($curl)
{
    if ($curl == "") {
        return false;
    }
    $timeout = 5;
    $con = curl_init();
    curl_setopt($con, CURLOPT_URL, $curl);
    curl_setopt($con, CURLOPT_HEADER, false);
    curl_setopt($con, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($con, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($con, CURLOPT_TIMEOUT, (int)$timeout);
    $c_res = curl_exec($con);
    curl_close($con);
    if ($c_res) {
        return $c_res;
    } else {
        return false;
    }
}

/**
 * php发送curl的Post请求
 * $url：url地址
 * $udata 发送的post值
 */
function req_Post($url, $udata)
{
    $timeout = 5;
    $con = curl_init();
    curl_setopt($con, CURLOPT_URL, $url);
    curl_setopt($con, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($con, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($con, CURLOPT_POST, true);
    curl_setopt($con, CURLOPT_POSTFIELDS, $udata);
    curl_setopt($con, CURLOPT_HEADER, false);
    curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($con, CURLOPT_TIMEOUT, (int)$timeout);
    $p_res = curl_exec($con);
    curl_close($con);
    if ($p_res) {
        return $p_res;
    } else {
        return false;
    }
}
/**
 * 文件上传
 * $fileSize：文件大小（传入int类型，单位:B）
 * $fileType 文件类型 （传入sting类型）
*/
function fileUpload($fileSize,$fileType){
    // 获取表单上传文件 例如上传了001.jpg
    $file = request()->file('file');
    try {
        //10M
        validate(['file'=>['filesize'=>$fileSize, 'fileExt'=>$fileType]])->check(['file'=>$file]);

        // 输出uploads/20220608\\2a412343630adc2b67d3d3e2c723a2cd.jpg
        $img_url= \think\facade\Filesystem::disk('public')->putFile( 'uploads', $file);
        $savename =  str_replace('\\', '/', $img_url);
        // 输出 http://127.0.0.1/public/storage/uploads/20220608\\2a412343630adc2b67d3d3e2c723a2cd.jpg
        $url = $_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST'].'/storage/'.$savename;
        $carousel_url_name = '/storage/'.$savename;
        return ['status'=>200,'msg'=>'上传成功！','path'=>$url,'del_url'=>$carousel_url_name];

    } catch (\think\exception\ValidateException $e) {
        return ['status'=>500,'msg'=>$e->getMessage(),'path'=>''];
    }
}

/**
 * 订单号
 * 雪花算法生成唯一id测试中: string
 * $length 取数据的长度
*/
function genAppNo($length=6){
    $datacenterId = rand(1, 4);//数据id
    $machineId = rand(1,31);//机器id
    $sf = new SnowFlake($datacenterId, $machineId);
    $nextId = strval($sf->nextId());
    return date("ymd").substr($nextId, $length);
}
/**
 * 导入sheet单张工作表数量excel数据
 *  根据业务注意修改$city的内容
*/
function importExcel(){
    $file = request()->file('file');
    $savename = [];
    try {

        // 验证文件大小，名称等是否正确10M
        validate(['file'=>['filesize'=>10485760, 'fileExt'=>'xls,xlsx']])->check(['file'=>$file]);
        // 将文件保存到本地
        $savename= \think\facade\Filesystem::disk('public')->putFile( 'topic', $file);
        // 截取后缀
        $fileExtendName = substr(strrchr($savename, '.'), 1);
        // 有Xls和Xlsx格式两种
        if ($fileExtendName == 'xlsx') {
            $reader = IOFactory::createReader('Xlsx');
        } else {
            $reader = IOFactory::createReader('Xls');
        }

        $reader->setReadDataOnly(TRUE);//忽略任何格式的信息
        $spreadsheet = $reader->load(public_path() . 'storage/' . $savename); //载入excel表格
        $worksheet = $spreadsheet->getActiveSheet();//获取数据
        $sheet = $spreadsheet->getSheet(0);   //excel中的第一张sheet
        $highestRow = $worksheet->getHighestRow(); // 总行数
        $highestColumn = $worksheet->getHighestColumn(); // 总列数
        Coordinate::columnIndexFromString($highestColumn);
        $lines = $highestRow - 1;
        if ($lines <= 0) {
            return ['status'=>500,'msg'=>'数据不能为空！'];
            exit();
        }
        // 直接取出excle中的数据
        $data = $spreadsheet->getActiveSheet()->toArray();
        // 删除第一个元素（表头）
        array_shift($data);
        $city = [];
        foreach($data as $k=>$v) {
            $city[$k]['activity_name'] = $v[0];
            $city[$k]['user_name'] = $v[1];
            $city[$k]['user_phone'] = $v[2];
            $city[$k]['user_company'] = $v[3];
            $city[$k]['user_post'] = $v[4];
        }
        Db::table("activity")->insertAll($city);
        try {
            return ['status'=>200,'msg'=>'数据导入成功！'];
        } catch (Exception $e) {
            return ['status'=>500,'msg'=>$e->getMessage()];
        }


    } catch (ValidateException $e) {
        return json(['status'=>500,'data'=>$e->getMessage()]);
    }
}



/**
 * 导出excel表
 * $data：要导出excel表的数据，接受一个二维数组
 * $name：excel表的表名
 * $head：excel表的表头，一维数组
 * $key：$data中对应表头的键的数组，一维数组
 * 备注：表头（对应列数）不能超过26；
 */
function exportExcel($name='表名', $data=[], $head=[], $keys=[])
{
    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();

    // $sheet->getDefaultRowD$spreadsheet->getProperties()

    $sheet->setTitle($name);//设置当前工作表标题

    //设置表头
    foreach ($head as $key => $value) {
        $sheet->setCellValueByColumnAndRow($key+1, 1, $value);
    }

    //设置内容
    foreach ($data as $row=>$item) {
        foreach ($keys as $key=>$value) {
             $sheet->setCellValueByColumnAndRow($key+1, $row+2, $item[$value]." ");
        }
    }
    $writer = new Xlsx($spreadsheet);

    //合并单元格 合并后，赋值只能给A1，开始的坐标。
    // $sheet->mergeCells('A2:A3');//合并单元格
    //$sheet->mergeCellsByColumnAndRow(1,2,1,3);//使用数字单元格坐标合并单元格
    // $sheet->unmergeCellsByColumnAndRow(1,2,1,3);//使用数字单元格坐标拆分单元格

    //1.下载到服务器
    //$writer->save($name.'.xlsx');

    //2.输出到浏览器
    //header('Content-Type: application/vnd.ms-excel');//xls
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//xlsx
    header('Content-Disposition: attachment;filename="'.$name.'.xlsx"');
    header('Cache-Control: max-age=0');

    $writer->save('php://output');
    //删除清空：
    $spreadsheet->disconnectWorksheets();
    unset($spreadsheet);
    exit;
}

/**
 * 生成账号和加密密码
 * @param $admin_name 用户名
 * @param $admin_password 密码
 * @param $admin_create_time 创建时间
 *
 **/
function set_password($name,$password){
    $data = [];
    $data['admin_name'] = $name;
    $data['admin_status'] = 0;
    $data['admin_password'] = password_hash($password,PASSWORD_DEFAULT);
    $data['admin_create_time'] = date("Y-m-d H:i:s",time());
    return $data;
}

/**
 * 验证密码
 * @param $input_password 输入的密码
 * @param  $user_password 用户数据库密码
*/
function checkPassword($input_password,$user_password){
    if(password_verify(trim($input_password),$user_password)){
        return ['status'=>200,'msg'=>"验证正确"];
    }else{
        return ['status'=>500,'msg'=>"验证错误"];
    }
}

/**
 * 生成验签
 * @param $uid 用户id
 * @return mixed
 */
function signToken($uid){
    $key='abcdefg';         //自定义的一个随机字串用户于加密中常用的 盐  salt
    $token = array(
        "iss" => $key,
        //"aud" => $id,//接收人，也就是发给谁
        "iat" => time(),//签发时间,当前时间
        "nbf" => time()+3,//生效时间,在生成时间后一点点
        'exp' => time()+10800,//过期时间，三个小时
        'data'=> ['uid'=>$uid]//自定义信息
    );

    //  print_r($token);
    $jwt = JWT::encode($token, $key, "HS256");  //生成了 token
    return $jwt;
}

/**
 * 验证token
 * @param $token
 * @return array|int[]
 */
function checkToken($token){
    $result["token"] = $token;
    $key='abcdefg';     //自定义的一个随机字串用户于加密中常用的 盐  salt
    try {
        //延长有效期1分钟
        JWT::$leeway = 60;
        //对token解码，得到的一个对象，所以直接转成数组
        $data = (array)JWT::decode($token,new Key($key, 'HS256'));
        //获取token里面的相关信息并赋值给数据集
        $result['data'] = $data['data'];
        //定义Result变量的status字段
        $result['status'] = 10001;
        //验证通过后返回$result数据集
        return $result;
        //如果验证失败，catch以下错误
    }catch (SignatureInvalidException $exception){
        //定义result数据集状态码status和data的默认值
        $result['status'] = 10002;
        $result['data']   = '验证失败！请重新登录';
        return $result;
    }catch (BeforeValidException $exception){
        //定义result数据集状态码status和data的默认值
        $result['status'] = 10003;
        $result['data']   = 'token未生效，请稍后！';
        return $result;
    }catch (ExpiredException $exception){
        //定义result数据集状态码status和data的默认值
        $result['status'] = 10004;
        $result['data']   = '登录过期，请重新登录！';
        return $result;
    }catch (Exception $exception){
        //定义result数据集状态码status和data的默认值
        $result['status'] = 10005;
        $result['data']   = '未知错误，请重新登录！';
        return $result;
    }
}

/**
 * 生成二维码海报 (执行后直接输出显示)
 *
 * @param string $bg_filename 背景图片文件名, 可以是网络图片
 * @param string $qrcode_filename 二维码图片文件名, 可以是网络图片
 * @param integer $qrcode_width 二维码定义宽度
 * @param integer $qrcode_height 二维码定义高度
 * @param integer $x 二维码距左边
 * @param integer $y 二维码距顶边
 * @return void
 */
function out_poster(string $bg_filename, string $qrcode_filename, int $qrcode_width, int $qrcode_height, int $x, int $y)
{
    $stream_opts = [
        "ssl" => [
            "verify_peer"=>false,
            "verify_peer_name"=>false,
        ]
    ];
    // 背景图file_get_contents($url, false, stream_context_create($stream_opts));
    $bg_im = imagecreatefromstring(file_get_contents($bg_filename,false,stream_context_create($stream_opts)));

    // 二维码
    $qrcode_blob = file_get_contents($qrcode_filename,false,stream_context_create($stream_opts));
    $qrcode_im = imagecreatefromstring($qrcode_blob);
    list($width_orig, $height_orig) = getimagesizefromstring($qrcode_blob);

    // 缩放二维码
    $new_qrcode = imagecreatetruecolor($qrcode_width, $qrcode_height);
    imagecopyresampled($new_qrcode, $qrcode_im, 0, 0, 0, 0, $qrcode_width, $qrcode_height, $width_orig, $height_orig);
    imagedestroy($qrcode_im);


    // 透明度
    $alpha = 100;

    // 合并图片
    imagecopymerge($bg_im, $new_qrcode, $x, $y, 0, 0, $qrcode_width, $qrcode_height, $alpha);

    // 合并输出格式
    header('Content-type: image/jpeg');

    imagejpeg($bg_im);
    // 释放资源
    imagedestroy($bg_im);
    imagedestroy($new_qrcode);
    exit;
}



